<template>
    <div class="ranking-manage">
        <div class="manage-header">
            <h2>排行管理</h2>
            <div class="header-actions">
                <el-select v-model="currentRankType" placeholder="选择排行类型" @change="getRankingList"
                    class="rank-type-select">
                    <el-option v-for="item in rankTypes" :key="item.value" :label="item.label"
                        :value="item.value"></el-option>
                </el-select>
                <el-button type="primary" @click="openAddDialog" class="add-button">
                    <el-icon>
                        <plus />
                    </el-icon> 新增排行
                </el-button>
            </div>
        </div>

        <!-- 数据表格 -->
        <el-table :data="rankingList" border v-loading="loading" class="ranking-table">
            <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
            <el-table-column prop="rankType" label="排行类型" width="120" align="center">
                <template #default="scope">
                    {{ getRankTypeName(scope.row.rankType) }}
                </template>
            </el-table-column>
            <el-table-column prop="rank" label="排名" width="80" align="center"></el-table-column>
            <el-table-column label="视频信息">
                <template #default="scope">
                    <div class="video-info-cell">
                        <el-image class="video-cover" :src="scope.row.coverUrl" fit="cover"
                            :preview-src-list="[scope.row.coverUrl]">
                            <template #error>
                                <div class="image-error">
                                    <el-icon><picture-filled /></el-icon>
                                    <span>加载失败</span>
                                </div>
                            </template>
                        </el-image>
                        <div class="video-details">
                            <div class="video-title">{{ scope.row.title }}</div>
                            <div class="video-uploader">UP主: {{ scope.row.username }}</div>
                        </div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="score" label="分值" width="120" align="center"></el-table-column>
            <el-table-column label="自动/手动" width="100" align="center">
                <template #default="scope">
                    <el-tag :type="scope.row.isManual ? 'warning' : 'success'" effect="dark">
                        {{ scope.row.isManual ? '手动设置' : '自动计算' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="状态" width="90" align="center">
                <template #default="scope">
                    <el-tag :type="scope.row.status === 1 ? 'success' : 'info'" effect="dark">
                        {{ scope.row.status === 1 ? '显示' : '隐藏' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right" align="center">
                <template #default="scope">
                    <div class="table-actions">
                        <el-tooltip content="编辑" placement="top">
                            <el-button size="small" type="primary" @click="handleEdit(scope.row)" circle>
                                <el-icon>
                                    <edit />
                                </el-icon>
                            </el-button>
                        </el-tooltip>
                        <el-tooltip content="删除" placement="top">
                            <el-button size="small" type="danger" @click="handleDelete(scope.row)" circle>
                                <el-icon>
                                    <delete />
                                </el-icon>
                            </el-button>
                        </el-tooltip>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <!-- 空数据展示 -->
        <el-empty v-if="rankingList.length === 0 && !loading" description="暂无排行数据" class="empty-data">
            <el-button type="primary" @click="openAddDialog">
                <el-icon>
                    <plus />
                </el-icon> 添加排行
            </el-button>
        </el-empty>

        <!-- 分页组件 -->
        <el-pagination v-if="rankingList.length > 0" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" :current-page="pagination.currentPage" :page-sizes="[10, 20, 30, 50]"
            :page-size="pagination.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
            background class="pagination">
        </el-pagination>

        <!-- 新增/编辑对话框 -->
        <el-dialog :title="dialogTitle" v-model="dialogVisible" width="600px" @closed="resetForm" destroy-on-close
            class="ranking-dialog" :close-on-click-modal="false">
            <div class="dialog-content">
                <el-form :model="rankingForm" :rules="rules" ref="rankingForm" label-width="100px" class="ranking-form">
                    <el-form-item label="排行类型" prop="rankType">
                        <el-select v-model="rankingForm.rankType" placeholder="选择排行类型" class="rank-type-input">
                            <el-option v-for="item in rankTypes" :key="item.value" :label="item.label"
                                :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="排名" prop="rank">
                        <el-input-number v-model="rankingForm.rank" :min="1" :max="100"
                            controls-position="right"></el-input-number>
                    </el-form-item>

                    <el-form-item label="关联视频" prop="vid">
                        <div class="video-search-container">
                            <el-autocomplete v-model="videoSearchInput" :fetch-suggestions="queryVideos"
                                placeholder="请输入视频标题搜索" @select="handleVideoSelect" :trigger-on-focus="false"
                                class="video-search" clearable popper-class="video-search-popper">
                                <template #default="{ item }">
                                    <div class="video-item">
                                        <img class="video-cover-small" :src="item.coverUrl || ''" alt="视频封面"
                                            @error="handleImageError($event)">
                                        <div class="video-info">
                                            <div class="video-title">{{ item.title || '未知标题' }}</div>
                                            <div class="video-uploader">UP主: {{ item.username || '未知用户' }}</div>
                                        </div>
                                    </div>
                                </template>
                            </el-autocomplete>

                            <div v-if="selectedVideo.vid" class="selected-video-info">
                                <el-tag closable type="success" @close="removeSelectedVideo">
                                    <el-icon><video-camera /></el-icon>
                                    已选择: {{ selectedVideo.title || '未知视频' }}
                                </el-tag>
                            </div>
                            <div v-else class="empty-video-tip">
                                <el-alert type="info" :closable="false">
                                    请搜索并选择视频，输入2个字符以上开始搜索
                                </el-alert>
                            </div>
                        </div>
                    </el-form-item>

                    <el-form-item label="分值" prop="score">
                        <el-input-number v-model="rankingForm.score" :min="0"
                            controls-position="right"></el-input-number>
                        <span class="form-tip">根据排行类型对应不同含义，如播放量、点赞数等</span>
                    </el-form-item>

                    <el-form-item label="设置方式" prop="isManual">
                        <el-radio-group v-model="rankingForm.isManual">
                            <el-radio :label="true">手动设置</el-radio>
                            <el-radio :label="false">自动计算</el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item label="状态" prop="status">
                        <el-switch v-model="rankingForm.status" :active-value="1" :inactive-value="0" active-text="显示"
                            inactive-text="隐藏" inline-prompt class="status-switch">
                        </el-switch>
                    </el-form-item>
                </el-form>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false" plain>取 消</el-button>
                    <el-button type="primary" @click="submitForm" :loading="submitting" :disabled="submitting">
                        {{ submitting ? '提交中...' : '确 定' }}
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script>
export default {
    name: "RankingManage",
    data() {
        return {
            loading: false,
            submitting: false, // 提交表单的加载状态
            rankingList: [],
            currentRankType: "hot",
            rankTypes: [
                { label: "热门榜", value: "hot" },
                { label: "新人榜", value: "newcreator" },
                { label: "原创榜", value: "original" },
                { label: "播放榜", value: "play" },
                { label: "点赞榜", value: "like" },
                { label: "投币榜", value: "coin" },
                { label: "收藏榜", value: "collect" }
            ],
            pagination: {
                currentPage: 1,
                pageSize: 10,
                total: 0
            },
            dialogVisible: false,
            dialogTitle: "新增排行",
            rankingForm: {
                id: null,
                rankType: "hot",
                rank: 1,
                vid: null,
                score: 0,
                isManual: true,
                status: 1
            },
            rules: {
                rankType: [
                    { required: true, message: "请选择排行类型", trigger: "change" }
                ],
                rank: [
                    { required: true, message: "请设置排名", trigger: "blur" }
                ],
                vid: [
                    { required: true, message: "请选择视频", trigger: "change" }
                ]
            },
            videoSearchInput: "",
            selectedVideo: {},
            uploadHeaders: {
                Authorization: `Bearer ${localStorage.getItem('teri_token') || ''}`
            }
        };
    },
    created() {
        // 获取排行类型
        this.getRankTypes();
    },
    methods: {
        // 获取排行类型
        async getRankTypes() {
            try {
                const res = await this.$get("/admin/ranking/types");
                console.log("获取排行类型结果:", res.data);
                if (res.data && res.data.code === 200 && Array.isArray(res.data.data) && res.data.data.length > 0) {
                    // 如果后端返回了排行类型列表，使用后端数据
                    this.rankTypes = res.data.data.map(type => ({
                        label: type.name,
                        value: type.code
                    }));
                    console.log("设置排行类型:", this.rankTypes);
                } else {
                    console.warn("未获取到排行类型数据，使用默认值");
                }
            } catch (error) {
                console.error("获取排行类型错误:", error);
            } finally {
                // 无论是否成功获取类型，都加载排行列表
                this.getRankingList();
            }
        },

        // 获取排行榜列表
        async getRankingList() {
            this.loading = true;
            try {
                console.log("正在获取排行榜列表，类型:", this.currentRankType);
                const res = await this.$get("/admin/ranking/list", {
                    params: {
                        rankType: this.currentRankType,
                        page: this.pagination.currentPage,
                        pageSize: this.pagination.pageSize
                    }
                });
                console.log("排行榜列表结果:", res.data);
                if (res.data && res.data.code === 200) {
                    if (res.data.data && res.data.data.records) {
                        this.rankingList = res.data.data.records || [];
                        this.pagination.total = res.data.data.total || 0;

                        // 确保所有必要字段都有值
                        this.rankingList = this.rankingList.map(item => {
                            return {
                                ...item,
                                coverUrl: item.coverUrl || '',
                                title: item.title || '未知标题',
                                username: item.username || '未知用户',
                                score: item.score || 0,
                                isManual: typeof item.isManual === 'boolean' ? item.isManual : true
                            };
                        });
                    } else {
                        this.rankingList = [];
                        this.pagination.total = 0;
                        console.warn("排行榜数据结构不符合预期:", res.data);
                    }
                } else {
                    this.$message.error(res.data ? (res.data.message || "获取排行列表失败") : "获取排行列表失败");
                }
            } catch (error) {
                console.error("获取排行列表错误:", error);
                this.$message.error("网络错误，获取排行列表失败");
            } finally {
                this.loading = false;
            }
        },

        // 打开新增对话框
        openAddDialog() {
            this.dialogTitle = "新增排行";
            this.resetForm();
            this.rankingForm.rankType = this.currentRankType;
            this.dialogVisible = true;
        },

        // 处理编辑
        async handleEdit(row) {
            this.dialogTitle = "编辑排行";
            this.resetForm();
            try {
                const res = await this.$get(`/admin/ranking/${row.id}`);
                if (res.data && res.data.code === 200 && res.data.data) {
                    const data = res.data.data;
                    this.rankingForm = {
                        id: data.id,
                        rankType: data.rankType || 'hot',
                        rank: data.rank || 1,
                        vid: data.vid || null,
                        score: data.score || 0,
                        isManual: typeof data.isManual === 'boolean' ? data.isManual : true,
                        status: data.status || 1
                    };
                    if (data.vid) {
                        this.selectedVideo = {
                            vid: data.vid,
                            title: data.videoTitle || '未知标题',
                            coverUrl: data.coverUrl || '',
                            username: data.username || '未知用户'
                        };
                    }
                    this.dialogVisible = true;
                } else {
                    this.$message.error(res.data ? (res.data.message || "获取排行详情失败") : "获取排行详情失败");
                }
            } catch (error) {
                console.error("获取排行详情错误:", error);
                this.$message.error("网络错误，获取排行详情失败");
            }
        },

        // 处理删除
        handleDelete(row) {
            this.$confirm("确认删除该排行?", "提示", {
                confirmButtonText: "确认",
                cancelButtonText: "取消",
                type: "warning"
            }).then(async () => {
                try {
                    const res = await this.$axios({
                        method: 'delete',
                        url: `/api/admin/ranking/${row.id}`,
                        headers: {
                            'Authorization': `Bearer ${localStorage.getItem('teri_token') || ''}`
                        }
                    });

                    if (res.data.code === 200) {
                        this.$message.success("删除成功");
                        this.getRankingList();
                    } else {
                        this.$message.error(res.data.message || "删除失败");
                    }
                } catch (error) {
                    console.error("删除排行错误:", error);
                    this.$message.error("网络错误，删除失败");
                }
            }).catch(() => { });
        },

        // 获取排行类型名称
        getRankTypeName(type) {
            const found = this.rankTypes.find(item => item.value === type);
            return found ? found.label : type;
        },

        // 查询视频列表
        async queryVideos(queryString, callback) {
            if (queryString.length < 2) {
                callback([]);
                return;
            }

            try {
                console.log("搜索视频:", queryString);
                const res = await this.$get("/admin/video/search", {
                    params: { keyword: queryString }
                });
                console.log("视频搜索结果:", res.data);
                if (res.data && res.data.code === 200 && Array.isArray(res.data.data)) {
                    callback(res.data.data || []);
                } else {
                    console.warn("视频搜索返回的数据结构不符合预期");
                    callback([]);
                }
            } catch (error) {
                console.error("搜索视频错误:", error);
                callback([]);
            }
        },

        // 处理图片加载错误
        handleImageError(e) {
            e.target.src = '';
        },

        // 选择视频
        handleVideoSelect(item) {
            console.log("选择的视频:", item);
            this.selectedVideo = {
                vid: item.vid,
                title: item.title || '未知标题',
                coverUrl: item.coverUrl || '',
                username: item.username || '未知用户'
            };
            this.rankingForm.vid = item.vid;
            this.videoSearchInput = "";
        },

        // 移除选择的视频
        removeSelectedVideo() {
            this.selectedVideo = {};
            this.rankingForm.vid = null;
        },

        // 提交表单
        submitForm() {
            console.log("提交的排行表单数据:", this.rankingForm);
            console.log("选择的视频:", this.selectedVideo);

            this.$refs.rankingForm.validate(async valid => {
                if (valid) {
                    if (!this.rankingForm.vid) {
                        this.$message.error("请选择关联视频");
                        return;
                    }

                    this.submitting = true;
                    const isEdit = this.rankingForm.id !== null;
                    const method = isEdit ? "put" : "post";
                    const url = isEdit ? `/admin/ranking/${this.rankingForm.id}` : "/admin/ranking";

                    // 确保传递所有必要字段
                    const formData = {
                        ...this.rankingForm,
                        // 补充必要数据
                        videoTitle: this.selectedVideo.title || '',
                        username: this.selectedVideo.username || '',
                        coverUrl: this.selectedVideo.coverUrl || ''
                    };

                    try {
                        const res = await this.$axios({
                            method: method,
                            url: `/api${url}`,
                            data: formData,
                            headers: {
                                'Content-Type': 'application/json',
                                'Authorization': `Bearer ${localStorage.getItem('teri_token') || ''}`
                            }
                        });

                        if (res.data && res.data.code === 200) {
                            this.$message.success(isEdit ? "更新成功" : "添加成功");
                            this.dialogVisible = false;
                            this.getRankingList();
                        } else {
                            this.$message.error(res.data ? (res.data.message || (isEdit ? "更新失败" : "添加失败")) : "操作失败");
                        }
                    } catch (error) {
                        console.error(isEdit ? "更新错误:" : "添加错误:", error);
                        this.$message.error(isEdit ? "更新失败" : "添加失败");
                    } finally {
                        this.submitting = false;
                    }
                } else {
                    console.error("表单验证失败");
                }
            });
        },

        // 重置表单
        resetForm() {
            if (this.$refs.rankingForm) {
                this.$refs.rankingForm.resetFields();
            }
            this.rankingForm = {
                id: null,
                rankType: this.currentRankType,
                rank: 1,
                vid: null,
                score: 0,
                isManual: true,
                status: 1
            };
            this.selectedVideo = {};
            this.videoSearchInput = "";
        },

        // 处理分页大小变化
        handleSizeChange(size) {
            this.pagination.pageSize = size;
            this.pagination.currentPage = 1;
            this.getRankingList();
        },

        // 处理页码变化
        handleCurrentChange(page) {
            this.pagination.currentPage = page;
            this.getRankingList();
        }
    }
}
</script>

<style scoped>
.ranking-manage {
    padding: 30px;
    background-color: #fff;
    border-radius: 12px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
    min-height: calc(100vh - 120px);
    margin: 20px;
}

.manage-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;
}

.manage-header h2 {
    font-size: 22px;
    font-weight: 600;
    color: #333;
    margin: 0;
    position: relative;
    padding-left: 14px;
}

.manage-header h2::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 4px;
    height: 22px;
    background-color: #409EFF;
    border-radius: 2px;
}

.header-actions {
    display: flex;
    align-items: center;
    gap: 15px;
}

.rank-type-select {
    width: 150px;
}

.rank-type-input {
    width: 100%;
}

.add-button {
    padding: 9px 16px;
    font-weight: 500;
}

/* 表格样式 */
.ranking-table {
    border-radius: 8px;
    overflow: hidden;
    margin-bottom: 20px;
    border: 1px solid #ebeef5;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.03);
}

/* 视频信息样式 */
.video-info-cell {
    display: flex;
    align-items: center;
    padding: 5px;
}

.video-cover {
    width: 120px;
    height: 70px;
    margin-right: 15px;
    object-fit: cover;
    border-radius: 6px;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.video-details {
    flex: 1;
    overflow: hidden;
}

.video-title {
    font-size: 14px;
    font-weight: 500;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    margin-bottom: 5px;
}

.video-uploader {
    font-size: 12px;
    color: #909399;
}

.image-error {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 70px;
    color: #909399;
}

/* 表格操作按钮样式 */
.table-actions {
    display: flex;
    justify-content: center;
    gap: 12px;
}

/* 分页样式 */
.pagination {
    margin-top: 24px;
    text-align: right;
    padding: 12px 0;
}

/* 空数据样式 */
.empty-data {
    margin: 80px auto;
    text-align: center;
}

/* 对话框样式 */
:deep(.ranking-dialog) {
    border-radius: 8px;
    overflow: hidden;
}

:deep(.ranking-dialog .el-dialog__header) {
    padding: 20px 24px;
    margin-bottom: 0;
    position: relative;
    border-bottom: 1px solid #f0f0f0;
}

:deep(.ranking-dialog .el-dialog__title) {
    font-size: 18px;
    font-weight: 600;
    color: #333;
}

:deep(.ranking-dialog .el-dialog__headerbtn) {
    top: 20px;
}

:deep(.ranking-dialog .el-dialog__body) {
    padding: 24px;
}

:deep(.ranking-dialog .el-dialog__footer) {
    padding: 16px 24px;
    border-top: 1px solid #f0f0f0;
    display: flex;
    justify-content: center;
}

.dialog-content {
    max-height: 60vh;
    overflow-y: auto;
    overflow-x: hidden;
    padding-right: 5px;
}

/* 滚动条样式 */
.dialog-content::-webkit-scrollbar {
    width: 6px;
}

.dialog-content::-webkit-scrollbar-thumb {
    background-color: #ddd;
    border-radius: 3px;
}

.dialog-content::-webkit-scrollbar-track {
    background-color: #f5f5f5;
    border-radius: 3px;
}

.ranking-form {
    width: 100%;
}

/* 表单项样式 */
:deep(.el-form-item) {
    margin-bottom: 22px;
}

:deep(.el-form-item__label) {
    font-weight: 500;
}

.form-tip {
    color: #909399;
    font-size: 13px;
    margin-left: 10px;
}

/* 视频搜索与展示样式 */
.video-search-container {
    width: 100%;
}

.video-search {
    width: 100%;
}

.video-item {
    display: flex;
    align-items: center;
    padding: 10px 0;
}

.video-cover-small {
    width: 80px;
    height: 45px;
    border-radius: 4px;
    object-fit: cover;
    margin-right: 12px;
    background-color: #f5f7fa;
    border: 1px solid #ebeef5;
}

.video-info {
    flex: 1;
    overflow: hidden;
}

.video-title {
    font-size: 14px;
    font-weight: 500;
    color: #303133;
    margin-bottom: 4px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.video-uploader {
    font-size: 12px;
    color: #909399;
}

.selected-video-info {
    margin-top: 12px;
}

.selected-video-info .el-tag {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    padding: 0 10px;
    height: 32px;
}

/* 按钮样式 */
.dialog-footer {
    display: flex;
    justify-content: center;
    gap: 16px;
}

.dialog-footer .el-button {
    padding: 10px 24px;
    min-width: 100px;
    font-size: 14px;
    font-weight: 500;
}

.status-switch {
    width: 90px;
}

.video-search-popper {
    width: 400px;
}

.empty-video-tip {
    margin-top: 10px;
}
</style>